﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DDS.IoT.Mqtt
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = string.Empty;
            if (args.Length == 0)
            {
                Console.WriteLine("选择：1.服务端 2.客户端");
                s = Console.ReadLine();
            }
            else
            {
                s = args[0];
            }
            if (s == "1")
            {
                StartHost(args);
            }else if (s == "2")
            {
                ClientTest(args);
            }
            Console.ReadLine();
        }

        private static void StartHost(string[] args)
        {
            MqttHostCom driver = new MqttHostCom();
            driver.OnPushData += Driver_OnPushDataHost;
            string server = "*";
            int port = 1883;
            if (args.Length > 2)
            {
                server = args[1];
                port = Convert.ToInt32(args[2]);
            }
            var extData = Newtonsoft.Json.JsonConvert.SerializeObject(new { server = server, port = port});
            driver.Init(1, extendData: extData);
            driver.Open();
            Console.ReadLine();
        }

        private static void Driver_OnPushDataHost(string id, dynamic data)
        {
            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(data));
        }

        private static void ClientTest(string[] args)
        {
            MqttClientCom driver = new MqttClientCom();
            driver.OnPushData += Driver_OnPushData;
            Console.Write("请输入clientid：");
            var clientid = Console.ReadLine();
            var extData = Newtonsoft.Json.JsonConvert.SerializeObject(new { server = "localhost", port = 1883, clientid = clientid });
            //var extData = Newtonsoft.Json.JsonConvert.SerializeObject(new { server = "broker.emqx.io", port = 1883, clientid = clientid });
            driver.Init(1, extendData: extData);
            driver.Open();
            driver.Command("Subscribe", Newtonsoft.Json.JsonConvert.SerializeObject(new { topic = "/dds/iot/mqtt/test1", level = 0 }));
            Thread.Sleep(1000);
            while (true)
            {
                Console.Write("请输入负载消息：");
                var pdata = Console.ReadLine();
                driver.Command("Publish", Newtonsoft.Json.JsonConvert.SerializeObject(new { topic = "/dds/iot/mqtt/test", data = pdata }));
                Console.WriteLine("已发布");
            }
            Console.ReadLine();
        }

        private static void Driver_OnPushData(string id, dynamic data)
        {

            Console.WriteLine("接收到数据：" + Newtonsoft.Json.JsonConvert.SerializeObject(data));
        }
    }
}
